//
//  UIScrollView+Scrollable.swift
//  
//
//  Created by tangbl93 on 2021/2/25.
//

import UIKit

// MARK: UIScrollView
extension UIScrollView: Scrollable {}
public extension Scrollable where Self: UIScrollView {
    
    func yx_scrollToTop(animated: Bool = true) {
        setContentOffset(
            CGPoint(x: CGFloat(0), y: {
                guard #available(iOS 11, *) else { return -contentInset.top }
                return -adjustedContentInset.top
            }()),
            animated: animated
        )
    }
    
    func yx_scrollToBottom(_ animated: Bool = true) {
        // https://stackoverflow.com/q/952412
        setContentOffset(
            CGPoint(x: 0, y: max(contentSize.height - bounds.size.height + contentInset.bottom, 0)),
            animated: animated
        )
    }
}

// MARK: UITableView
public extension Scrollable where Self: UITableView {
    
    func yx_scrollToTop(animated: Bool = true) {
        guard let firstIndexPath = self.yx_firstIndexPath else { return }
        self.scrollToRow(at: firstIndexPath, at: .top, animated: animated)
    }
    
    func yx_scrollToBottom(_ animated: Bool = true) {
        guard let lastIndexPath = self.yx_lastIndexPath else { return }
        self.scrollToRow(at: lastIndexPath, at: .bottom, animated: animated)
    }
}

// MARK: UICollectionView
public extension Scrollable where Self: UICollectionView {
    
    func yx_scrollToTop(animated: Bool = true) {
        guard let firstIndexPath = self.yx_firstIndexPath else { return }
        self.scrollToItem(at: firstIndexPath, at: .top, animated: animated)
    }
    
    func yx_scrollToBottom(_ animated: Bool = true) {
        guard let lastIndexPath = self.yx_lastIndexPath else { return }
        self.scrollToItem(at: lastIndexPath, at: .bottom, animated: animated)
    }
}
